import _ from "lodash";
import { ICmpnt } from "./ICmpnt";
import { IContainerField } from "./IContainer";


type CmpntFunction = (name: string) => ICmpnt;


export function setConf(cmpnt: ICmpnt, fn: CmpntFunction): void {
  let sourceCmpnt = fn(cmpnt.ctl.name);
  let targetProps = cmpnt.props; //目标，最终对象
  let sourceProps = sourceCmpnt.props; //提供数据源的对象
  targetProps.bind = sourceProps.bind;
  cmpnt.ctl = sourceCmpnt.ctl;

  //合并props

  mergeObject(targetProps, sourceProps);

  cmpnt.children?.forEach((element: ICmpnt) => {
    setConf(element, fn);
  });

  //处理字段类组件
  if (targetProps.fields && targetProps.fields.length > 0) {
    targetProps.fields.forEach((ef: IContainerField) => {
      ef.cmpnts?.forEach((e: ICmpnt) => {
        setConf(e, fn);
      });
    });
  }
}
function mergeObject(target: any, source: any): void {
  //根据source,将新增属性追加到target上
  _.keys(source).forEach((key: string) => {
    if (!target.hasOwnProperty(key)) {
      target[key] = source[key];
      return;
    }
    let targetValue = target[key];
    if (_.isPlainObject(targetValue)) {
      mergeObject(targetValue, source[key]);
    }
  });




  //根据source,将target中多余的属性删除
  if (_.keys(source).length > 0) {
    _.keys(target).forEach((key: string) => {
      if (!source.hasOwnProperty(key)) {
        delete target[key];
      }
    });
  }

  //重拍顺序。
  _.keys(source).forEach((key: string) => {
    if (target.hasOwnProperty(key)) {
      let value = target[key];
      delete target[key];
      target[key] = value;
    }
  });


}